package nl.hva.three2learn.controller;

import java.util.List;
import java.util.Locale;

import nl.hva.three2learn.dao.CourseDao;
import nl.hva.three2learn.model.Course;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/search")
public final class SearchController {

	@Autowired
	private MessageSource messageSource;

	@Autowired
	private CourseDao courseDao;

	@RequestMapping(value = "/{query}", method = RequestMethod.GET)
	public ModelAndView search(Locale locale,
			@PathVariable("query") String query, Model model) {

		ModelAndView modelAndView = new ModelAndView("search/results");
		modelAndView.addObject("query", query);

		// Same as: <spring:message code="course.title.viewing"/> but cannot
		// put the tag in the title attribute of the wrapper tag
		modelAndView.addObject("title",
				messageSource.getMessage("search.title.results", null, locale));

		List<Course> courses = courseDao.findCoursesLike(query);
		model.addAttribute("courses", courses);
		
		return modelAndView;
	}
	
	@RequestMapping(value = "/search", method = RequestMethod.POST)
	public String doSearch(@RequestParam("query") String query) {
		return "redirect:/search/" + query;
	}
	
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public ModelAndView search2(Locale locale, Model model) { 
	
		ModelAndView modelAndView = new ModelAndView("search/search");
		modelAndView.addObject("title",
				messageSource.getMessage("search.wrapper", null, locale));
		return modelAndView;
	}
}
	

